#ifndef TaskScheduler_h_
#define  TaskScheduler_h_
#include <stdint.h>
#include <functional>
#include <chrono>
#include <thread>
#include <mutex>
#include <list>
#include <map>

class Event
{
public:
	int64_t Wait()
	{
		std::unique_lock<decltype(m_MutexCondition)> lock{ m_MutexCondition };
		m_Condition.wait(lock, [&]()->bool { return ret != -1; }); // suspend and wait ...	
		return ret;
	}
	void Set(int64_t re)
	{
		std::unique_lock<decltype(m_MutexCondition)> lock(m_MutexCondition);
		ret = re;
		m_Condition.notify_one();
	}
	std::mutex m_MutexCondition;
	std::condition_variable m_Condition;
	int64_t ret = -1;
};

class Timer
{
public:
	Timer(int64_t delay, std::function<bool()> cb) : m_iDelay(delay), m_cb(cb) {};
	~Timer() {};
	int64_t m_iDelay = 0;
	std::function<bool()> m_cb;
	int64_t m_iTimerId = -1;
};
using Task = std::function<void()>; //定义类型

class TaskScheduler
{
public:
	TaskScheduler();
	~TaskScheduler();
	int64_t getCurrentTicket();
	int32_t StartRun();

	void StopRun();
	int64_t AddTimer(int64_t iDelay, std::function<bool()> fcb);

	void PostTask(Task task);

	void InvokTask(Task task);

	int32_t DelTimer(int64_t timerId);

	void RunLoop();
	

private:
	int64_t getMinDelay();
	int64_t flushDelayTask(uint64_t now_time);
	//int32_t addTimerInner(std::shared_ptr<Timer>& _Timer)

	std::thread *m_loopThread;

	std::mutex _mutex;
	bool m_bStart = false;
	bool m_bExitThread = false;
	std::condition_variable _condition;
	std::list<Task> _queue;
	std::multimap<uint64_t, std::shared_ptr<Timer> > m_delayTask;
	int64_t m_iTimerId = 0;
	std::thread::id _loopThreadId;
};


#endif